var mh;
var jump = 0 ; 
var history_list = $.cookie("mh_reading_history")?eval($.cookie("mh_reading_history")):[];

Array.prototype.remove = function( indexNum ){
	if( isNaN( indexNum )|| indexNum > this.length){
		return false;
	}

	this.splice( indexNum, 1 );
}

function drag(evt)
{
	evt = evt || window.event;

	if (document.all && evt.button != 1)
	{
		return false;
	}
        var pic = document.getElementById("pic");
	oX = 2 * document.documentElement.scrollLeft;
	cX = document.documentElement.scrollLeft - evt.screenX;
	oY = 2 * document.documentElement.scrollTop;
	cY = document.documentElement.scrollTop - evt.screenY;

	if (pic.addEventListener)
	{
		pic.addEventListener("mousemove", moveHandler, true);
		pic.addEventListener("mouseup", upHandler, true);
	}
	else if (pic.attachEvent)
	{
		pic.setCapture( );
		pic.attachEvent("onmousemove", moveHandler);
		pic.attachEvent("onmouseup", upHandler);
		pic.attachEvent("onlosecapture", upHandler);
	}
	else
	{
		var oldmovehandler = pic.onmousemove;
		var olduphandler = pic.onmouseup;
		pic.onmousemove = pic;
		pic.onmouseup = pic;
	}

	if (evt.stopPropagation) evt.stopPropagation( );
	else evt.cancelBubble = true;

	if (evt.preventDefault) evt.preventDefault( );
	else evt.returnValue = false;

	if (evt.stopPropagation) evt.stopPropagation( );
	else evt.cancelBubble = true;

	pic.style.cursor = "move";

	function moveHandler(evt)
	{
		mX = evt.screenX + cX;
		mY = evt.screenY + cY;
		window.scrollTo(oX - mX, oY - mY);

		if (evt.stopPropagation) evt.stopPropagation( );
		else evt.cancelBubble = true;
	}

	function upHandler(evt)
	{
		pic.style.cursor = "auto";

		if (pic.removeEventListener)
		{
			pic.removeEventListener("mouseup", upHandler, true);
			pic.removeEventListener("mousemove", moveHandler, true);
		}
		else if (pic.detachEvent)
		{
			pic.detachEvent("onlosecapture", upHandler);
			pic.detachEvent("onmouseup", upHandler);
			pic.detachEvent("onmousemove", moveHandler);
			pic.releaseCapture( );
		}
		else
		{
			pic.onmouseup = olduphandler;
			pic.onmousemove = oldmovehandler;
		}
		if (evt.stopPropagation) evt.stopPropagation( );
		else evt.cancelBubble = true;
	}
}
function getQueryParam(param){
	var reg = new  RegExp("(^|&)"+ param +"=([^&]*)(&|$)");  
	var  r  =  window.location.search.substr(1).match(reg);  
	if (r!=null) return unescape(r[2]);return   null;  
}
if(!mh){
	 mh  = {
	 	init:function(){
			var page_no  = parseInt(getQueryParam("p"));
			if(isNaN(page_no)){
				this.page = 1;
			}else{
	 			this.page = Math.max(1,Math.min(page_no,len));
			}
	 	},
		onload:  function (){			
	 		base_url = curChapterUrl;
			this.setReadingHistory();
			if($.cookie('_mh_reading_color')){
				$('body').addClass($.cookie('_mh_reading_color'));
			}else{
				$('body').addClass('black');
			}
			
			//toolbar状态是否展开
			if($.cookie("_mh_reading_toolbar")=='up'){
				$(".tool-bar").css("top",'-36px');
				$('.show-time .down').show();
				$('.show-time .up').hide();
			}else{
				$('.show-time .down').hide();
			}
			
			//toolbar
			$('.show-time .up').click(function(){
				mh.toolbarShrink();
			});
			
			$('.show-time .down').click(function(){
				mh.toolbarExpand();
			});			
			
			//章节目录
			$(".see-list").click(function(){
				$(".chapter-list").toggle();
			});
			$(".chapter-list .close").click(function(){
				$(".chapter-list").hide();
			});
			
			//加载当前页的图片后，预加载
			$(".show-pic img").attr("src",img_base_url+img_list[this.page-1]).load(function(){
				mh.preLoad();
				mh.moveImgBind();
				$('#pic').dblclick(function(){
				   mh.nextPage();
				});
			});
			
			$(".next_page").click(function(){
				mh.nextPage();
			});
			
			$(".prev_page").click(function(){
				mh.prevPage();
			});
			
			$(".next_chapter").click(function(){
				mh.nextChapter();
			});
			
			$(".prev_chapter").click(function(){
				mh.prevChapter();
			});
			
			$(".color-change a").click(function(){
				var color = $(this).attr("color");
				$.cookie("_mh_reading_color",color,{path:"/",expires:2592000000});//记录这次的选择
				$("body").removeClass("blue white black").addClass(color);				
			});

			$("*").keyup(function(event){				
				if((event.keyCode == 37 ) && window.jump==0){
					window.jump = 1;
					mh.prevPage();
				}else if( (event.keyCode == 39 ) && window.jump ==0){
					window.jump = 1;
					mh.nextPage();
				}
				return false;
			});
			
			$("#cbAutosize").click(function () {
				var c = $(this).attr("class");
				var autosite = true;
				if (c == "c-white-select")
					autosite = false;
				$.cookie("autosize", autosite, { path: "/" });
				var width = $("#pic").width();
				var height = $("#pic").height();
				if (autosite) {
					if (width > ($(window).width() - 20)) {
						$("#pic").css("width", $(window).width() - 20);
						$("#readImgDiv").attr("style", "z-index:1;position:relative;margin:0 auto;width:"+$(window).width() - 20+"px;");
					}
					$("#cbAutosize").removeClass("c-white-noselect").addClass("c-white-select");
				} else {
					location.reload(false);
					$("#cbAutosize").removeClass("c-white-select").addClass("c-white-noselect");
				}
			});	
		},
		
		refreshCurrPage:function() {
			setTimeout(function(){
				location.href = base_url + '?p=' + String(mh.page);
			},0);
		},
		
		//下一页
		nextPage:function(){
			if((this.page+1)>len){
				if (parseInt(nextChapterCount) == 1) {
					if(window.confirm("已经是最后一页了，是否观看下一章节？")){
						setTimeout(function(){
							location.href = nextChapterUrl;
						},0);
					}
				} else {
					if(window.confirm("已经是最后一页了，是否返回目录？")){
						setTimeout(function(){
							location.href = chapter_list_url;
						},0);
					}
				}
				return false;
			}else{
				setTimeout(function(){
					location.href = base_url + '?p=' + String(mh.page+1);
				},0);
				
			}
		},
		
		prevPage:function(){
			setTimeout(function(){
				location.href = base_url + '?p=' + String(Math.max(1,mh.page-1));
			},0);
		},
		
		prevChapter:function(){
			if (curChapterUrl == prevChapterUrl) {
				alert("已经是第一章了哦");
				return false;
			}
			setTimeout(function(){
				location.href = prevChapterUrl;
			},0);
		},
		
		nextChapter:function(){
			if (curChapterUrl == nextChapterUrl) {
				alert("已经是最后一章了哦");
				return false;
			}
			setTimeout(function(){
				location.href = nextChapterUrl;
			},0);
		},
		
		showPagination:function(){
			var minShowPage = 1;
			var maxShowPage = len;
			var pageinationStr = '';
			pageinationStr+='<div class="page"><form action="'+curChapterUrl+'" action="get">';
			pageinationStr+='<a onclick="mh.jumpToPage(1);" href="javascript:void(0);">首页</a>';
			if(mh.page==1){
				pageinationStr+='<span class="pre"></span>'
			}else{
				pageinationStr+='<a class="pre" onclick="mh.prevPage();" href="javascript:void(0);"></a>'
			}
			if (len > 6) {
				if(mh.page <4){
					minShowPage = 1;
				}else{
					minShowPage = Math.min(parseInt(this.page-3),parseInt(len-4));
				}
				for(i=0;i<=4;i++){
					if(mh.page==minShowPage+i){
						pageinationStr+='<span class="now">'+mh.page+'</span>';
					}
					else{
						pageinationStr+='<a href="javascript:void(0);" onclick="mh.jumpToPage('+String(minShowPage+i)+')" >'+String(minShowPage+i)+'</a>';
					}
				}
			} else {
	            for (i = 1; i <= len; i++) {
	                if (i == mh.page) {
	                	pageinationStr += "<span class=\"now\">" + i + "</span>";
	                } else {
	                	pageinationStr += ("<a href=\"#\" onclick=\"mh.jumpToPage('"+String(i)+"')\" >" + i + "</a>");
	                }
	            }
	        }
			if(mh.page==len){
				pageinationStr+='<span class="next"></span>'
			}else{
				pageinationStr+='<a class="next" onclick="mh.nextPage();" href="javascript:void(0);"></a>';
			}
			pageinationStr+='<a onclick="mh.jumpToPage(len);" href="javascript:void(0);">末页</a>';
			pageinationStr+='<span class="go-page"><input type="text" class="page_no" name="p" />&nbsp;<button type="submit" class="jump">GO</button></span>';
			pageinationStr+="</form></div>";
			document.write(pageinationStr);
		},
		
		showSelectPagination:function(){
			var minShowPage = 1;
			var maxShowPage = len;
			var pageinationStr = '';
			if(mh.page==1){
				pageinationStr+='<a class="btn" href="javascript:void(0);">上一页</a>&nbsp;';
			}else{
				pageinationStr+='<a class="btn" onclick="mh.prevPage();" href="javascript:void(0);">上一页</a>&nbsp;';
			}
			
			pageinationStr += '<select onchange="mh.jumpToPage(this.value)">';
            for (i = 1; i <= len; i++) {
                if (i == mh.page) {
                	pageinationStr += "<option selected value="+i+">第" + i + "页</option>";
                } else {
                	pageinationStr += ("<option value="+i+">第" + i + "页</option>");
                }
            }
            pageinationStr += "</select>";
            
			if(mh.page==len){
				pageinationStr+='&nbsp;<a class="btn" href="javascript:void(0);">下一页</a>';
			}else{
				pageinationStr+='&nbsp;<a class="btn" onclick="mh.nextPage();" href="javascript:void(0);">下一页</a>';
			}
			document.write(pageinationStr);
		},
		
		jumpToPage:function(page){
			setTimeout(function(){
				location.href = base_url + '?p=' + String(Math.min(Math.max(page,1),len));
			},0);
			
		},
		/*
		*预先加载
		*/
		preLoad: function(){
			var pre_num = 5;//预加载张数
			var i = 1;//游标
			
			while(i<=pre_num && mh.page<=len){
				if(mh.page+i-1>=len){//判断是否已到了章节末尾
					return false;
				}
				mh.appendImgObj((mh.page+i-1));
				i++;
			}
		},
		
		moveImgBind:function(){
			document.getElementById('pic').onmousedown = function (event){drag(event)};
		},
		
		appendImgObj: function(index){
		    $("#preload_img").append("<img src=\"" + img_base_url + img_list[index] + "\" />");
			$("#preload_img img").hide();
		},
		
		toolbarExpand:function(){
			$(".tool-bar").animate({top:'0'},500);
			$(".show-time .up").show();
			$(".show-time .down").hide();
			$.cookie("_mh_reading_toolbar","down");
		},
		
		toolbarShrink:function(){
			$(".tool-bar").animate({top:'-36'},500);
			$(".show-time .up").hide();
			$(".show-time .down").show();
			$.cookie("_mh_reading_toolbar","up");
		},
		
		setReadingHistory:function(){			
			var obj = {book_id:info.b_id,chapter_id:info.c_id,page_no:this.page,book_name:escape(comic_name),chapter_name:escape(chapter_name)};
		    
			if(history_list.length==20){
				history_list.remove(0);
			}
			
			var len =  history_list.length;
			for(var i=0;i<len;i++){
				if(typeof(history_list[i])!='undefined' && history_list[i].book_id == info.b_id){
					history_list.remove(i);
				}
			}
			
			history_list.push(obj);
			
			$.cookie("mh_reading_history",this.arrayToSource(history_list),{path:"/",expires:2592000000});
		},
		arrayToSource:function(list){
			var str = "";
			if(typeof(list)=="object" && typeof(list.splice)=='function'){
				str+="[";

				for(var i=0;i<list.length;i++){
					if(typeof(list[i])=='object' && typeof(list[i].book_id)!='undefined' &&  typeof(list[i].chapter_id)!='undefined' && typeof(list[i].page_no)!='undefined' && typeof(list[i].book_name) != 'undefined'){
						str +="{book_id:"+parseInt(list[i].book_id)+","+"chapter_id:"+parseInt(list[i].chapter_id)+","+"page_no:"+parseInt(list[i].page_no)+","+"book_name:'"+escape(list[i].book_name)+"'";
						if (typeof(list[i].chapter_name) !='undefined') {
							str += ","+"chapter_name:'"+escape(list[i].chapter_name)+"'";
						} else {
							str += ","+"chapter_name:''";
						}
						str +="}";
						if(i<list.length-1) str +=",";
					}
				}
				str+="]";
			}
			return str;
		}
	}
}

function fangdasuoxiao(typeval) {
    var imgWidth = $("#pic").width();
    var widthUpNum = 80;
    if (typeval == "up") {
        $("#pic").attr("width", imgWidth + widthUpNum);
    } else {
        $("#pic").attr("width", imgWidth - widthUpNum);
    }
}